package com.pesking.core.sqlparser.processor;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import com.pesking.core.utils.ThisServerUtil;
import org.apache.commons.lang3.StringUtils;

import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;

public class UrlSaveSqlParameterHandler extends VarcharSqlParameterHandler {
	@Override
	public String getTitle() {
		return "URL存储参数";
	}

	@Override
	public String getDescription() {
		return "根据指定的参数值转化为标准的URL格式";
	}

	@Override
	public void setParameter(PreparedStatement ps, Parameter parameter, int index,SqlParameter sqlParameter) throws SQLException {
		String name = sqlParameter.getName();
		String value = parameter.getParameter(name);
		if (!StringUtils.isBlank(value)) {
			if (value.startsWith("#/") 
					|| value.startsWith("^/")
					|| value.startsWith("#/")
					|| value.startsWith("$/")) {
				//以这些开头的，无须再处理
			}
			else {
				String cp = ThisServerUtil.getContextPath();
				boolean appendFrontendFlag = !StringUtils.isBlank(ThisServerUtil.getFrontendUrl());
				if (StringUtils.isBlank(cp)){
					if (value.indexOf("/") == 0) {
						if (appendFrontendFlag) {
							value = "^" + value;
						}
						else {
							value = "@" + value;
						}
					}
				}
				else {
					if (value.indexOf(cp) == 0) {
						if (appendFrontendFlag) {
							value = "^" + value.substring(cp.length());
						}
						else {
							value = "@" + value.substring(cp.length());
						}
					}
				}
				
			}
			
		}
		
		if (value == null) {
			ps.setNull(index, java.sql.Types.VARCHAR);
		}
		else {
			ps.setString(index, value);
		}
	}

	@Override
	public void handle(StringBuilder sbSQL, Parameter requestParameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		sbSQL.append("?");
		processors.add(sqlParameter);
	}

	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"URL_SAVE"});
	}
}
